<?php

namespace app\admin\model;

use think\Model;
use traits\model\SoftDelete;
use addons\kuerp\model\Flows;
use app\admin\model\kuerp\Prefix;
use Exception;
use think\Db;

class ScoreApply extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'score_apply';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'check_time_text',
        'check_status_text',
        'pay_status_text',
    ];
    
    public function getPayStatusList()
    {
        return ['0' => __('Pay_status 0'), '1' => __('Pay_status 1')];
    }

    public function getPayStatusTextAttr($value, $data)
    {
        $value = $value ? $value : $data['pay_status'];
        $list = $this->getPayStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    
    public function getCheckStatusList()
    {
        return ['0' => __('Check_status 0'), '1' => __('Check_status 1'), '2' => __('Check_status 2'), '3' => __('Check_status 3')];
    }

    public function getCheckStatusTextAttr($value, $data)
    {
        $value = $value ? $value : $data['check_status'];
        $list = $this->getCheckStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getCheckTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['check_time']) ? $data['check_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCheckTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function getApplyInfo($where)
    {  
        return $this->where($where)->find();
    }

    public function addScoreApply($params)
    {
        $params['check_status'] = $params['check_status'] ?? 1;
        $admin = Admin::info();
        $params['admin_id'] = $admin->id;
        $total_score = 0;
        $caijiaUserModel = new \app\common\model\caijiatong\User();
        if (empty($params['apply_data'])) throw new Exception('申请明细不能为空');
        $apply_data = $params['apply_data'];
        foreach ($apply_data as $k=>$v){
            $caijia_user = $caijiaUserModel->getUserInfo($v['mobile']);
            if(!$caijia_user){
                throw new Exception('材价通会员账号'.$v['mobile'].'不存在');
            }
            if ($v['score'] <= 0) {
                throw new Exception('积分不能小于等于0');
            }
            $total_score += $v['score'];
        }
        $code = (new Prefix())->getCodes('',29);
        $params['apply_code'] = $code;
        $params['total_score'] = $total_score;
        $params['apply_data'] = is_array($params['apply_data']) ? json_encode($params['apply_data'], 256) : $params['apply_data'];
        //是否在审核流程中
        //获取审批流程
        $flows = Db::name('flows')->where('relation_type', 'score')->where('status', 1)->find();
        if (!empty($flows)){
            $flows['flow_items'] = json_decode($flows['flow_items'], true);
            //判断流程中是否有当前用户审核
            $examine_index = 0;
            foreach ($flows['flow_items'] as $key => $value) {
                if (in_array($params['admin_id'], explode(',',$value['admin_id'])) ) {
                    $examine_index = $key + 1;
                    // break;
                }
            }
            $params['check_flow_id'] = $flows['id'];
            $params['check_step_sort'] = $examine_index;
        }
        
        $apply = new self;

        $result = $apply->allowField(true)->save($params);
        if (!$result) {
            throw new Exception($apply->getError());
        }
        $lastId = $apply->id;
        if ($params['check_status'] == 1) {
            $flow = Flows::getFlowByTypes(Flows::SCORE_STATUS);
            //发送审批通知
            Flows::sendStepRecord($flow, Flows::SCORE_STATUS, $lastId);
        }
        return $lastId;
    }

    public function editScoreApply($params, $row)
    {
        $total_score = 0;
        $caijiaUserModel = new \app\common\model\caijiatong\User();
        if (empty($params['apply_data'])) throw new Exception('申请明细不能为空');
        $apply_data = $params['apply_data'];
        foreach ($apply_data as $k=>$v){
            $caijia_user = $caijiaUserModel->getUserInfo($v['mobile']);
            if(!$caijia_user){
                throw new Exception('材价通会员账号'.$v['mobile'].'不存在');
            }
            if ($v['score'] <= 0) {
                throw new Exception('积分不能小于等于0');
            }
            $total_score += $v['score'];
        }
        $params['total_score'] = $total_score;
        $params['apply_data'] = is_array($params['apply_data']) ? json_encode($params['apply_data'], 256) : $params['apply_data'];
        if($row['check_status'] != 2){
            //获取审批流程
            $flows = Db::name('flows')->where('relation_type', 'expense')->where('status', 1)->find();
            if (!empty($flows)){
                $flows['flow_items'] = json_decode($flows['flow_items'], true);
                //判断流程中是否有当前用户审核
                $examine_index = 0;
                foreach ($flows['flow_items'] as $key => $value) {
                    if (in_array($row['admin_id'], explode(',',$value['admin_id'])) ) {
                        $examine_index = $key + 1;
                        // break;
                    }
                }
                // $params['check_flow_id'] = $flows['id'];
                $params['check_step_sort'] = $examine_index;
            }
            $params['check_status'] = $params['check_status'] ?? 1;
            // $params['check_step_sort'] = 0;
            $params['check_uids'] = '';
            $params['check_time'] = 0;
            $params['check_remark'] = '';
            $params['updatetime'] = time();
        }

        $apply = new self;
        // 调用当前模型对应的User验证器类进行数据验证
        $result = $apply->isUpdate(true)->allowField(true)->save($params, ['id' => $row['id']]);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception($apply->getError());
        }
        
        return true;
    }

    public function admin()
    {
        return $this->belongsTo('app\admin\model\Admin', 'admin_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
